/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/closest-binary-search-tree-value
   @Language: C++
   @Datetime: 19-05-07 11:01
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

// Method 1, Time O(n), Space O(n), Time 246ms
class Solution {
	void inorder(TreeNode *root, vector<int> &vs){
		if(root==NULL) return;
		inorder(root->left,vs);
		vs.push_back(root->val);
		inorder(root->right,vs);
	}
public:
	/**
	 * @param root: the given BST
	 * @param target: the given target
	 * @param k: the given k
	 * @return: k values in the BST that are closest to the target
	 */
	vector<int> closestKValues(TreeNode * root, double target, int k) {
		// write your code here
		vector<int> vs, res;
		inorder(root,vs);
		if(vs.size()<=k) return vs;
		int mid = lower_bound(vs.begin(),vs.end(),target)-vs.begin();
		if(mid>=vs.size()) mid=vs.size()-1;
		for(int i=mid, j=mid+1; res.size()<k;){
			if(i<0) res.push_back(vs[j++]);
			else if (j>=vs.size()) res.push_back(vs[i--]);
			else if(abs(target-vs[i])<abs(target-vs[j]))
				res.push_back(vs[i--]);
			else res.push_back(vs[j++]);
		}
		return res;
	}
};
